<%@ page language="java" contentType="text/html; charset=utf-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean"/>
<%@ page import="cn.hutool.crypto.digest.DigestAlgorithm" %>
<%@ page import="cn.hutool.crypto.digest.Digester" %>
<%@ page import="com.alibaba.fastjson.JSONArray" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="okhttp3.*" %>
<%@ page import="weaver.common.DateUtil" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.general.Util" %>
<%
    String fullDate = DateUtil.getFullDate();
    out.println(">>>>WeaSyncToMaycurCronJob>>>>>fullDate=" + fullDate + "<br/>");
    JSONObject responseJson = getToken();
    String status = Util.null2String(responseJson.getString("success"));
    String message = Util.null2String(responseJson.getString("message"));
    out.println(">>>>WeaSyncToMaycurCronJob>>>>>getToken>>>>status=" + status + ",message=" + message + "<br/>");
    if ("true".equals(status)) {
        JSONObject dataJson = responseJson.getJSONObject("data");
        String entCode = Util.null2String(dataJson.getString("entCode"));
        String tokenId = Util.null2String(dataJson.getString("tokenId"));
        String tlevels = getTlevel();
        String [] tlevelList =  tlevels.split(",");
        out.println(">>>>WeaSyncToMaycurCronJob>>>>>departmentBatchAdd>>>>tlevels=" + tlevels + "<br/>");
        JSONArray departmentsList = new JSONArray();
        for (String tlevel:tlevelList) {
            out.println(">>>>WeaSyncToMaycurCronJob>>>>>departmentBatchAdd>>>>tlevel=" + tlevel + "<br/>");
            //同步部门到每刻
            JSONArray departmentList = new JSONArray();
            rs.executeQuery("select a.id,a.departmentcode,a.departmentname,a.subcompanyid1,a.canceled,a.supdepid " +
                    "from hrmdepartment a join hrmdepartmentdefined b on a.id=b.deptid " +
                    "where isnull(b.sfytb,1) !=0 and a.tlevel=?",tlevel);
            while (rs.next()) {
                JSONObject departmentJson = new JSONObject();
                String departid = Util.null2String(rs.getString("id"));
                String departmentcode = Util.null2String(rs.getString("departmentcode"));
                String departmentname = Util.null2String(rs.getString("departmentname"));
                String subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
                String canceled = Util.null2String(rs.getString("canceled"));
                String supdepid = Util.null2String(rs.getString("supdepid"));
                departmentJson.put("departid", departid);
                departmentJson.put("businessCode", departmentcode);
                departmentJson.put("newBusinessCode", "");
                departmentJson.put("name", departmentname);
                String parentBizCode = "100" + subcompanyid1;
                if(!"0".equals(supdepid)){
                    parentBizCode =  getDepartmentCode(supdepid);
                }
                departmentJson.put("parentBizCode", parentBizCode);
                departmentJson.put("enabled", !"0".equals(canceled));
                departmentList.add(departmentJson);
                departmentsList.add(departmentJson);
            }
            out.println(">>>>WeaSyncToMaycurCronJob>>>>>departmentBatchAdd>>>>departmentList=" + departmentList + "<br/>");
            if (departmentList.size()>0) {
                String responseStr = departmentBatch(departmentList, entCode, tokenId);
                out.println(">>>>WeaSyncToMaycurCronJob>>>>>departmentBatchAdd>>>>responseStr=" + responseStr + "<br/>");
                JSONObject depresponseJson = JSONObject.parseObject(responseStr);
                String depstatus = depresponseJson.getString("success");
                String depdata = depresponseJson.getString("data");
                if ("true".equals(depstatus)) {
                    rs.executeUpdate("update hrmdepartmentdefined set sfytb=0 where isnull(sfytb,1) !=0 and deptid in (select id from hrmdepartment where tlevel='"+tlevel+"')");
                }
                if("false".equals(depstatus)) {
                    rs.executeUpdate("update hrmdepartmentdefined set sfytb=0 where isnull(sfytb,1) !=0 and deptid in (select id from hrmdepartment where tlevel='"+tlevel+"')");
                    JSONObject depdataJson = JSONObject.parseObject(depdata);
                    String errorDataStr = depdataJson.getString("errorData");
                    JSONArray errorDataArr = JSONArray.parseArray(errorDataStr);
                    for (int i = 0; i < errorDataArr.size(); i++) {
                        String key = errorDataArr.getJSONObject(i).getString("key");
                        String deptid = getDepartmentId(key);
                        rs.executeUpdate("update hrmdepartmentdefined set sfytb=1 where deptid='" + deptid + "' and isnull(sfytb,1) =0");
                    }
                }
            }
        }

        //同步人员到每刻-人员在职
        String ryzt = "0,1,2,3";
        String rylt = "4,5,6,7";
        JSONArray employeeList = new JSONArray();
        rs.executeQuery("select a.id,a.workcode,a.lastname,a.email,a.mobile,a.departmentid,b.field4,a.companystartdate,a.sex,a.managerid from hrmresource a join cus_fielddata b " +
                "on a.id=b.id where scope='HrmCustomFieldByInfoType' and scopeid='3' and isnull(b.field3,1) !=0 order by a.id");
        while (rs.next()) {
            JSONObject employeeJson = new JSONObject();
            String id = Util.null2String(rs.getString("id"));
            String workcode = Util.null2String(rs.getString("workcode"));
            String lastname = Util.null2String(rs.getString("lastname"));
            String email = Util.null2String(rs.getString("email"));
            String mobile = Util.null2String(rs.getString("mobile"));
            String departmentid = Util.null2String(rs.getString("departmentid"));
            String departmentCode = getDepartmentCode(departmentid);
            String joblevel = Util.null2String(rs.getString("field4"));
            String cbzx = getCbzx(id);
            String companystartdate = Util.null2String(rs.getString("companystartdate"));
            String sex = Util.null2String(rs.getString("sex"));
            String managerid = Util.null2String(rs.getString("managerid"));
            String resstatus = Util.null2String(rs.getString("status"));
            employeeJson.put("resourceid", id);
            employeeJson.put("employeeId", workcode);
            employeeJson.put("employeeName", lastname);
            employeeJson.put("email", email);
            employeeJson.put("phoneNo", mobile);
            JSONArray departments = new JSONArray();
            JSONObject departmentsJson = new JSONObject();
            departmentsJson.put("businessCode", departmentCode);
            departmentsJson.put("defaultDepartment", true);
            departmentsJson.put("supervisorEmployeeId", getWorkCode(managerid));
            departments.add(departmentsJson);
            employeeJson.put("departments", departments);
            JSONObject customObject = new JSONObject();
            customObject.put("CBZX", cbzx);
            employeeJson.put("customObject", customObject);
            if (ryzt.contains(resstatus)){
                resstatus = "ENABLE";
            }
            if (rylt.contains(resstatus)){
                resstatus = "DISABLE";
            }
            employeeJson.put("status", resstatus);
            employeeJson.put("hireDate", companystartdate);
            String subcompanyid = getsubcompanyid1(departmentid);
            employeeJson.put("defaultLegalEntityBizCode", "100"+subcompanyid);
            employeeJson.put("classPositionBizCode", joblevel);
            String gender = "0".equals(sex) ? "MAN" : "WOMAN";
            employeeJson.put("gender", gender);
            employeeJson.put("allowEmailAndPhoneBeNull", false);
            employeeList.add(employeeJson);
        }
        out.println(">>>>WeaSyncToMaycurCronJob>>>>>employeeBatchAdd>>>>employeeList=" + employeeList + "<br/>");
        if (employeeList.size()>0) {
            String responseStr = employeeBatch(employeeList, entCode, tokenId);
            out.println(">>>>WeaSyncToMaycurCronJob>>>>>employeeBatchAdd>>>>responseStr=" + responseStr + "<br/>");
            JSONObject empresponseJson = JSONObject.parseObject(responseStr);
            String empstatus = empresponseJson.getString("success");
            String empdata = empresponseJson.getString("data");
            if ("true".equals(empstatus)) {
                rs.executeUpdate("update cus_fielddata set field3=0 where scope='HrmCustomFieldByInfoType' and scopeid='3' and isnull(field3,1) !=0");
            }
            if ("false".equals(empstatus)) {
                rs.executeUpdate("update cus_fielddata set field3=0 where scope='HrmCustomFieldByInfoType' and scopeid='3' and isnull(field3,1) !=0");
                JSONObject empdataJson = JSONObject.parseObject(empdata);
                String errorDataStr = empdataJson.getString("errorData");
                JSONArray errorDataArr = JSONArray.parseArray(errorDataStr);
                for (int i = 0; i < errorDataArr.size(); i++) {
                    String key = errorDataArr.getJSONObject(i).getString("key");
                    String resourceid = getResourceId(key);
                    rs.executeUpdate("update cus_fielddata set field3=1 where scope='HrmCustomFieldByInfoType' and scopeid='3' and isnull(field3,1) =0 and id='" + resourceid + "'");
                }
            }
            //更新部门主管工号到每刻
            JSONArray departmentList1 = new JSONArray();
            for (int i = 0; i < departmentsList.size(); i++) {
                JSONObject departmentJson = new JSONObject();
                String departid = departmentsList.getJSONObject(i).getString("departid");
                String businessCode = departmentsList.getJSONObject(i).getString("businessCode");
                String name = departmentsList.getJSONObject(i).getString("name");
                String parentBizCode = departmentsList.getJSONObject(i).getString("parentBizCode");
                departmentJson.put("businessCode", businessCode);
                departmentJson.put("newBusinessCode", businessCode);
                departmentJson.put("name", name);
                departmentJson.put("parentBizCode", parentBizCode);
                String bmzgid = getDepartDefined(departid);
                String managerEmployeeId = getWorkCode(bmzgid);
                String[] managerEmployeeIds = {managerEmployeeId};
                departmentJson.put("managerEmployeeIds", managerEmployeeIds);
                departmentList1.add(departmentJson);
            }
            if (!departmentList1.isEmpty()) {
                responseStr = departmentBatch(departmentList1, entCode, tokenId);
                out.println(">>>>WeaSyncToMaycurCronJob>>>>>departmentBatchUpdate>>>>responseStr=" + responseStr);
            }
        }
    }
%>
<%!
    /**
     * 获取部门级别
     * @return
     */
    private static String getTlevel(){
        String tlevels = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select tlevel from hrmdepartment group by tlevel order by tlevel");
        while (rs.next()){
           String tlevel = Util.null2String(rs.getString(1));
           tlevels +="".equals(tlevels)?tlevel:","+tlevel;
        }
        return tlevels;
    }
    /**
     * 获取token
     * @return
     */
    public static JSONObject getToken() {
        String resultStr = "";
        JSONObject paramsJson = new JSONObject();
        // appCode 和appSecret请联系每刻工作人员
        String appCode = "AP3RRI7V8BH9AP";
        String appSecret = "ixVTcToV3bShWDHm5Kwl";
        long timestamp = System.currentTimeMillis();
        String url = "https://ng-uat.maycur.com/api/openapi/auth/login";
        String secret = getSecret(appCode, appSecret, timestamp);
        paramsJson.put("secret", secret);
        paramsJson.put("appCode", appCode);
        paramsJson.put("timestamp", timestamp);
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, paramsJson.toJSONString());
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            resultStr = response.body().string();
            System.out.println(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(resultStr);
    }

    /**
     * 生成密钥
     *
     * @param appCode
     * @param appSecret
     * @param timestamp
     * @return
     */
    public static String getSecret(String appCode, String appSecret, long timestamp) {
        Digester sha256 = new Digester(DigestAlgorithm.SHA256);
        return sha256.digestHex(appSecret + ":" + appCode + ":" + timestamp);
    }

    /**
     * 批量同步部门接口
     * @param departmentList
     * @param entCode
     * @param tokenId
     * @return
     */
    public static String departmentBatch(JSONArray departmentList, String entCode, String tokenId) {
        String url = "https://ng-uat.maycur.com/api/openapi/org/department/batch";
        return sendOKHttpRequest(departmentList.toJSONString(), url, entCode, tokenId);
    }

    /**
     * 员工批量同步接口
     * @param employeeList
     * @param entCode
     * @param tokenId
     * @return
     */
    public static String employeeBatch(JSONArray employeeList, String entCode, String tokenId) {
        String url = "https://ng-uat.maycur.com/api/openapi/employee/batch";
        return sendOKHttpRequest(employeeList.toJSONString(), url, entCode, tokenId);
    }

    /**
     * 获取部门自定义部门主管
     * @param deptid
     * @return
     */
    public static String getDepartDefined(String deptid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select bmzg from hrmdepartmentdefined where deptid=?", deptid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 获取部门编码
     * @param departid
     * @return
     */
    public static String getDepartmentCode(String departid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select departmentcode from hrmdepartment where id=?", departid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    /**
     * 获取部门Id
     * @param departmentcode
     * @return
     */
    public static String getDepartmentId(String departmentcode) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from hrmdepartment where departmentcode=?", departmentcode);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    /**
     * 获取分部ID
     * @param departid
     * @return
     */
    public static String getsubcompanyid1(String departid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select subcompanyid1 from hrmdepartment where id=?", departid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    /**
     * 获取员工工号
     * @param resourceid
     * @return
     */
    public static String getWorkCode(String resourceid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select workcode from hrmresource where id=?", resourceid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    /**
     * 获取成本中心
     * @param resourceid
     * @return
     */
    public static String getCbzx(String resourceid) {
        RecordSet rs = new RecordSet();
        String sql = "select field2 from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid='3' and id=?";
        rs.executeQuery(sql, resourceid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    /**
     * 获取员工id
     *
     * @param workcode
     * @return
     */
    public static String getResourceId(String workcode) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from hrmresource where workcode=?", workcode);
        rs.next();
        return com.weaver.general.Util.null2String(rs.getString(1));
    }

    /**
     * 发送http请求
     *
     * @param params
     * @param url
     * @return
     */
    public static String sendOKHttpRequest(String params, String url, String entCode, String tokenId) {
        String resultStr = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("entCode", entCode)
                    .addHeader("tokenId", tokenId)
                    .build();
            Response response = client.newCall(request).execute();
            resultStr = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }
%>